package com.fise.mwtvc.socket

import com.fise.mwtvc.socket.bean.UserModifyNotification
import com.fise.mwtvc.socket.bean.WsResponse
import com.fise.mwtvc.socket.bean.WsResponse.Companion.TYPE_OK
import com.google.gson.Gson
import com.google.gson.JsonDeserializationContext
import com.google.gson.JsonDeserializer
import com.google.gson.JsonElement
import java.lang.reflect.Type

class WsResponseDeserializer : JsonDeserializer<WsResponse> {
    private val gson = Gson()

    override fun deserialize(
        json: JsonElement,
        typeOfT: Type,
        context: JsonDeserializationContext
    ): WsResponse? {
        try {
            val rsp = gson.fromJson(json, WsResponse::class.java)
            val jsonObject = json.asJsonObject
            rsp.type = jsonObject["type"]?.asInt ?: TYPE_OK
            val dataElement = jsonObject["data"]
            val cls = WsResponse.run {
                when (rsp.type) {
                    TYPE_OK -> String::class.java
                    TYPE_USER -> UserModifyNotification::class.java
                    TYPE_CONFIG -> Long::class.java
                    else -> null
                }
            }
            if (cls != null) {
                if (cls == UserModifyNotification::class.java) {
                    rsp.data = gson.fromJson(json, cls)
                    return rsp
                }
                rsp.data = gson.fromJson(dataElement, cls)
            }
            return rsp
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
        return null
    }
}